from PySide6.QtWidgets import QMainWindow, QScrollArea, QMessageBox, QPushButton
from PySide6.QtCore import QRect
from PySide6.QtGui import Qt
from widgets.scriptWidgets.ScriptWidget import ScriptWidget


class SubScriptEditWindow(QMainWindow):
    def __init__(self, parent, script=None):
        super(SubScriptEditWindow, self).__init__(parent)

        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        self.setWindowTitle('编辑脚本')
        self.setFixedSize(419, 509)

        self.scrollScript = QScrollArea(self)
        self.scrollScript.setObjectName(u"scrollScript")
        self.scrollScript.setGeometry(QRect(0, 0, self.width(), self.height() - 40))
        self.scrollScript.setWidgetResizable(True)

        from widgets.ScriptContent import ScriptContent
        self.scriptContent = ScriptContent(script, initType='edit')
        self.scriptContent.setGeometry(QRect(0, 0, self.width(), self.height() - 40))
        self.scrollScript.setWidget(self.scriptContent)

        self.btnSave = QPushButton(self)
        self.btnSave.clicked.connect(self.close)
        self.btnSave.setText('保存')
        self.btnSave.setFixedSize(100, 35)
        self.btnSave.setGeometry(
            int(self.width() / 2 - 50), self.height() - 40,
            self.btnSave.width(), self.btnSave.height()
        )

    @property
    def data(self):
        # 返回一个脚本的content列表
        widgets = self.scrollScript.widget().children()
        result = []
        for widget in widgets:
            if not isinstance(widget, ScriptWidget):
                continue

            widgetData = widget.data
            if 'error' in widgetData.keys():
                QMessageBox.information(self, '保存', '保存失败' + widgetData['error'])
                return None

            result.append(widgetData)

        return result
